package com.topisv.tms.web.phone;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.entity.User;
import com.topisv.tms.entity.stock.CusStock;
import com.topisv.tms.entity.stock.moveStock.MoveStockBill;
import com.topisv.tms.repository.stock.CusStockDao;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiGoodsSkuService;
import com.topisv.tms.service.account.AccountService;
import com.topisv.tms.service.stock.CusStockService;
import com.topisv.tms.service.stock.moveStock.MoveStockBillService;

import net.sf.json.JSONObject;

@Controller
@RequestMapping(value = "/phone")
public class WMSMoveStockController {
	
	private static final Logger log = LoggerFactory.getLogger(WMSMoveStockController.class);
	
	@Autowired
    private CusStockDao cusStockDao;
	@Autowired
	private CusStockService cusStockService;
	@Autowired
	private EdiGoodsSkuService goodsService;
	@Autowired
	private MoveStockBillService msbService;
	@Autowired
	private AccountService accountService;
	@Autowired
	private CustomersService customersService;
	@Autowired
	private AreaGroupService warehouseService;
	/**
	 * 请求库位上sku信息
	 * @param warehouseCode 任务编号
	 * @param stockCode 库位号
	 * @param boxCode 箱位号
	 * @param response
	 */
	@RequestMapping(value = "ajaxQuerySkuByStock")
	public void ajaxQuerySkuByStock(
			@RequestParam(value = "warehouseCode") String warehouseCode,
			@RequestParam(value = "stockCode") String stockCode,
			@RequestParam(value = "customerCode",required=false) String customerCode,
			@RequestParam(value = "boxCode") String boxCode,
			@RequestParam(value = "sku") String sku,
		HttpServletResponse response,Model model) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			Map<String,Object> param = new HashMap<String,Object>();
			param.put("warehouseCode", warehouseCode);
			param.put("stockCode", stockCode);
			param.put("customerCode", customerCode);
			param.put("boxCode", boxCode);
			param.put("sku", sku);
			List<CusStock> cusStockList = cusStockService.findStockByParam(param);
			if(cusStockList==null||cusStockList.size()==0){
				json.put("status", "0");
				json.put("content", "库存信息不存在");
				return;
			}
			for (CusStock cusStock : cusStockList) {
				EdiGoodsSku goodsSku = goodsService.findByCustomerCodeAndSku(cusStock.getCustomerCode(), cusStock.getSku());
				if(goodsSku!=null){
					cusStock.setGoodsName(goodsSku.getSkuName());
				}
			}
			
			json.put("status", "1");
			json.put("content", "获取成功");
			json.put("cusStockList", cusStockList);
		} catch (Exception e) {
			log.error("error",e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		} finally{
		    out.print(json.toString());
		}
	}
	
	
	
	/**
	 * 生成移库单
	 * @param response
	 */
	@RequestMapping(value = "ajaxAddMoveBill")
	public void ajaxAddMoveBill(
			@RequestParam(value = "jobuuid") String jobuuid,
			@RequestParam(value = "warehouseCode") String warehouseCode,
			@RequestParam(value = "customerCode",required=false) String customerCode,
			@RequestParam(value = "stockCode") String stockCode,
			@RequestParam(value = "boxCode") String boxCode,
			@RequestParam(value = "sku") String sku,
			@RequestParam(value = "isSale") String isSale,
			@RequestParam(value = "moveNum") String moveNum,
		HttpServletResponse response,Model model) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			User curUser=this.accountService.findUserByJobuuid(jobuuid);
			
			
			MoveStockBill msb = new MoveStockBill();
			msb.setWarehouseCode(warehouseCode);
			msb.setCustomerCode(customerCode);
			msb.setOutStockCode(stockCode);
			msb.setOutBoxCode(boxCode);
			try{
				msb.setOutMoveNum(Integer.valueOf(moveNum));
			}catch(Exception e){
				log.error("error",e);
				json.put("status", "0");
				json.put("content", "移库数量必须是数字");
				return;
			}
			msb.setSku(sku);
			msb.setStatus("new");
			msb.setGoodsStatus(isSale);//sale:销售库存 unsale:不可销售库存
			msb.setCreateTime(new Date());
			msb.setCreateBy(curUser.getJobuuid());
			
			msbService.saveMoveStockBill(msb);
			
			
			List<MoveStockBill> moveList = msbService.findNoFinishMoveBill( warehouseCode,jobuuid);
			
			json.put("id", msb.getId());
			json.put("moveList", moveList);
			json.put("status", "1");
			json.put("content", "保存成功");
		} catch (Exception e) {
			log.error("error",e);
			json.put("status", "0");
			json.put("content", e.getMessage());
		} finally{
		    out.print(json.toString());
		}
	}
	
	
	/**
	 * 未完成移库单
	 * @param response
	 */
	@RequestMapping(value = "ajaxNoFinishMoveBill")
	public void ajaxNoFinishMoveBill(
			@RequestParam(value = "jobuuid") String jobuuid,
			@RequestParam(value = "warehouseCodes") String warehouseCodes,
		HttpServletResponse response,Model model) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			List<MoveStockBill> moveList = msbService.findNoFinishMoveBill( warehouseCodes,jobuuid);
			
			json.put("moveList", moveList);
			json.put("status", "1");
			json.put("content", "查询成功");
		} catch (Exception e) {e.printStackTrace();
			log.error("error",e);
			json.put("status", "0");
			json.put("content", e.getMessage());
		} finally {
		    out.print(json.toString());
		}
	}
	
	/**
	 * 单号查询移库单
	 * @param response
	 */
	@RequestMapping(value = "ajaxQueryMoveBillById")
	public void ajaxQueryMoveBillById(
			@RequestParam(value = "id") String id,
		HttpServletResponse response,Model model) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			MoveStockBill moveStockBill = null;
			try{
				moveStockBill = msbService.findOne(Long.valueOf(id));
			}catch(Exception e){
				log.error("error",e);
				json.put("status", "0");
				json.put("content", "移库数量必须是数字");
				return;
			}
			
			
			json.put("moveStockBill", moveStockBill);
			json.put("status", "1");
			json.put("content", "查询成功");
		} catch (Exception e) {e.printStackTrace();
			log.error("error",e);
			json.put("status", "0");
			json.put("content", e.getMessage());
		} finally{
		    out.print(json.toString());
		}
	}
	
	
	/**
	 * 执行移库操作
	 * @param response
	 */
	@RequestMapping(value = "ajaxExecuteMove")
	public void ajaxExecuteMove(
			@RequestParam(value = "jobuuid") String jobuuid,
			@RequestParam(value = "id") String moveId,
			@RequestParam(value = "stockCode") String stockCode,
			@RequestParam(value = "boxCode") String boxCode,
			@RequestParam(value = "sku") String sku,
			@RequestParam(value = "isSale") String isSale,
			@RequestParam(value = "moveNum") String moveNum,
		HttpServletResponse response,Model model) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			User curUser=this.accountService.findUserByJobuuid(jobuuid);
			
			MoveStockBill msb = msbService.findOne(Long.valueOf(moveId));
			if(msb==null){
				json.put("status", "0");
				json.put("content", "移库单不存在");
				return;
			}
			MoveStockBill toMsb = new MoveStockBill();
			try{
				toMsb.setId(Long.valueOf(moveId));
			}catch(Exception e){
				json.put("status", "0");
				json.put("content", "移库单号错误");
				return;
			}
			toMsb.setInStockCode(stockCode);
			toMsb.setInBoxCode(boxCode);
			toMsb.setSku(sku);
			toMsb.setGoodsStatus(isSale);//sale:销售库存 unsale:不可销售库存
			try{
				toMsb.setInMoveNum(Integer.valueOf(moveNum));
			}catch(Exception e){
				json.put("status", "0");
				json.put("content", "移库数量必须为数字");
				return;
			}
			toMsb.setUpdateBy(curUser.getJobuuid());
			toMsb.setUpdateTime(new Date());
			this.msbService.executeMoveStock(toMsb);
			MoveStockBill moveStockBill = msbService.findOne(Long.valueOf(moveId));
			
			json.put("moveStockBill", moveStockBill);
			json.put("status", "1");
			json.put("content", "保存成功");
		} catch (Exception e) {
			e.printStackTrace();
			log.error("error",e);
			json.put("status", "0");
			
			if (e instanceof HibernateOptimisticLockingFailureException) {
				json.put("content", "数据已更新，请重新提交！");
			} else {
				json.put("content", e.getMessage());
			}
		} finally{
		    out.print(json.toString());
		}
	}
	
	
	/**
	 * 根据库位，商品和仓库，获取系统中对应库位上的商家（货主）
	 * 
	 * @param 
	 * @return 
	 * @throws 
	 * @author <a href=mailto:libin@nryuncang.com>libin</a>
	 * @version 1.0.0
	 */
	@RequestMapping(value = "ajaxGetCustomers")
    public void ajaxGetCustomers(
            @RequestParam(value = "warehouseCode") String warehouseCode,
            @RequestParam(value = "stockCode") String stockCode,
            @RequestParam(value = "boxCode") String boxCode,
            @RequestParam(value = "sku") String sku,
        HttpServletResponse response) {

        JSONObject json = null;
        PrintWriter out = null;
        Map<String,String> customerCodes = new HashMap<String, String>();;
        try {
            json = new JSONObject();
            out = response.getWriter();
            
            List<CusStock> cusStockList = cusStockDao.loadStockNoCustomerCode(warehouseCode, stockCode, boxCode, sku);
            if(cusStockList==null||cusStockList.size()==0){
                json.put("status", "0");
                json.put("content", "库存信息不存在");
                return;
            }
            for (CusStock cusStock : cusStockList) {
                customerCodes.put(cusStock.getCustomerCode(),cusStock.getCustomer().getCustomerName());
            }
            
            json.put("status", "1");
            json.put("content", customerCodes);
        } catch (Exception e) {
            log.error("error",e);
            json.put("status", "0");
            json.put("content", "服务器异常");
        } finally{
            out.print(json.toString());
        }
    }
	
}

  

    
